<template>
  <div>
    <!-- 顶部的面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-s-promotion"></i> 后台管理</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 分割线 -->
    <el-divider></el-divider>

    <el-row :gutter="24">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>个人信息</span>
          </div>
          <div>
            <div style="text-align: center">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:10020/common/upload?module=avatar"
                  :show-file-list="false"
                  :headers="headers"
                  :on-success="handleAvatarSuccess">
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <ul class="list-group">
              <li class="list-group-item">
                <i class="el-icon-user-solid">用户名</i>
                <div class="pull-right">{{ userInfo.username }}</div>
              </li>
              <li class="list-group-item">
                <i class="el-icon-phone">电话号码</i>
                <div class="pull-right">{{ userInfo.phone }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>修改个人信息</span>
          </div>
          <el-form ref="form" :model="userInfo" :rules="rules" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userInfo.username" maxlength="30" disabled/>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
              <el-input v-model="userInfo.password" maxlength="50" show-password/>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userInfo.phone" maxlength="11"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="submit">保存</el-button>
              <el-button type="danger" size="mini" @click="close">关闭</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import BaseUrl from "@/http/BaseUrl";
import TokenAxios from "@/http/TokenAxios";

export default {
  data() {
    return {
      headers: {
        'Authorization': JSON.parse(localStorage.getItem('loginInfo')).token // 将 token 添加到请求头中
      },
      rules:{
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {min: 11, max: 11, message: '长度需为 11 个字符', trigger: 'blur'}
        ],
      },
      userInfo:{
        id: '',
        username: '',
        password: '',
        avatar: '',
        phone: '',
      },
      loginInfo: {},
    }
  },
  methods: {
    // 加载当前登录的用户信息
    loadCurrentLoginInfo() {
      let loginInfoString = localStorage.getItem('loginInfo');
      this.loginInfo = JSON.parse(loginInfoString);
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/' + this.loginInfo.id;
      console.log('url = ' + url)
      TokenAxios.get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000){
          this.userInfo = jsonResult.data;
        }else {
          let title = '操作失败';
          this.$alert(message, title,{
            confirmButtonText: '确定',
            callback:action => {}
          });
        }
      }).catch(error => {
        let title = '错误';
        let message = "执行程序过程中出现错误，请打开浏览器的控制台查看详细错误信息!";
        this.$alert(message,title,{
          confirmButtonText:'确定',
          callback:action => {}
        });
        console.log(error)
      })
    },
    // 修改头像
    handleAvatarSuccess(res, file) {
      this.userInfo.avatar = `http://localhost:10020/common/download?name=${res.content}`
      // 强制刷新一下
      this.$forceUpdate();
    },
    // 点击保存按钮
    submit(){
      this.$refs.form.validate((valid) => {
        if (valid){
          let message = '您确定修改信息吗？';
          this.$confirm(message,'提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.handleUpdate();
            location.reload();
          }).catch(() => {})
        } else {
          this.$message({
            message: '输入的信息不规范，请按照要求输入！',
            type: 'warning'
          });
        }
      })
    },
    // 处理保存功能
    handleUpdate(){
      let url = BaseUrl.ADMIN_ACCOUNT + '/users/userInfo/update';
      console.log('url = ' + url)
      this.userInfo.id=this.loginInfo.id;
      TokenAxios.post(url,this.userInfo).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 20000){
          this.$message({
            message: '修改信息成功！',
            type: 'success',
          });
          this.loadCurrentLoginInfo();
        }else if (jsonResult.state === 40400){
          this.$alert(jsonResult.message,'操作失败',{
            confirmButtonText: '确定',
            callback: action => {this.loadCurrentLoginInfo()}
          })
        }else {
          this.$alert(jsonResult.message,'操作失败',{
            confirmButtonText: '确定',
            callback: action => {}
          })
        }
      }).catch(error => {
        let title = '错误';
        let message = '程序执行过程出现错误，请打开浏览器的控制台查看详细错误信息!';
        this.$alert(message,title,{
          confirmButtonText: '确定',
          callback: action => {}
        })
        console.log(error)
      })
    },
    // 点击关闭按钮
    close(){
      this.$router.push('/admin/account/user')
    },
  },
  mounted() {
    this.loadCurrentLoginInfo();
  }
}
</script>

<style>
.clearfix::after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}

.list-group {
  padding-left: 0px;
  list-style: none;
}

.list-group-item {
  border-bottom: 1px solid #e7eaec;
  border-top: 1px solid #e7eaec;
  margin-bottom: -1px;
  padding: 11px 0px;
  font-size: 15px;
}

.pull-right {
  float: right !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>